package gao.xiaolei.controller;

import gao.xiaolei.dto.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import gao.xiaolei.exception.AuthException;
import gao.xiaolei.service.GroupService;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/group")
public class GroupController {

    @Resource(name = "GroupService")
    private GroupService groupService;

    @GetMapping("/class/{classId}")
    public List<TreeDto> getGroupTreeListByClass(@PathVariable("classId")String classId){
        return groupService.findByClasses(classId);
    }

    @GetMapping("/detail/{id}")
    public GroupOutDto getGroupDetail(@PathVariable("id")String id){
        return groupService.getGroupDetail(id);
    }

    @PostMapping("")
    public void addGroup(@RequestBody GroupInDto groupInDto){
        groupService.addClassesGroup(groupInDto);
    }

    @PutMapping("")
    public void updateGroup(@RequestBody GroupInDto groupInDto){
        groupService.updateClassesGroup(groupInDto);
    }

    @DeleteMapping("/{id}")
    public void deleteGroup(@PathVariable("id") String id){
        groupService.deleteClassesGroup(id);
    }

    @GetMapping("/leadingCadre/{leadingCadre}")
    public List<GroupDto> getGroupListByLeadingCadre(@PathVariable("leadingCadre") String leadingCadre){
        return groupService.getGroupDetailByLeadingCadre(leadingCadre);
    }

    @GetMapping("/member/{userId}")
    public List<GroupDto> getGroupListByMember(@PathVariable("userId") String userId){
        return groupService.getGroupDetailByGroupMember(userId);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseEnvelope<String>> handelError(Exception e) {
        e.printStackTrace();
        Integer code = null;
        if (e.getClass() == MissingServletRequestParameterException.class)
            code = 400;
        else if (e.getClass() == AuthException.class)
            code = 401;
        else
            code = 500;
        ResponseEnvelope<String> result = new ResponseEnvelope<String>(code, e.getMessage(), null);
        return new ResponseEntity<ResponseEnvelope<String>>(result, HttpStatus.valueOf(500));
    }
}
